package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.service.*;
import cn.wolfcode.luowowo.search.template.DestinationTemplate;
import cn.wolfcode.luowowo.search.template.StrategyTemplate;
import cn.wolfcode.luowowo.search.template.TravelTemplate;
import cn.wolfcode.luowowo.search.template.UserInfoTemplate;
import cn.wolfcode.luowowo.search.vo.SearchResult;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class ElasticsearchController {
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IUserInfoService userInfoService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private ITravelService travelService;

    @Reference
    private IStrategySearchService strategyTemplateService;
    @Reference
    private ITravelSearchService travelTemplateService;
    @Reference
    private IUserInfoSearchService userInfoTemplateService;
    @Reference
    private IDestinationSearchService destinationTemplateService;
    @Reference
    private ISearchService searchService;

    @RequestMapping("/q")
    public String query(@ModelAttribute("qo") SearchQueryObject qo, Model model){
        String viewName = null;
        //同一个地址,根据参数不同查询不同结果和跳转页面
        //使用SearchResult data来封装攻略/游记/用户的信息(里面有四个字段list)
        switch (qo.getType()){
            case SearchQueryObject.SEARCH_DEST ://需要dest, data, qo
                searchDest(qo, model);
                viewName = "index/searchDest";
                break;
            case SearchQueryObject.SEARCH_STRATEGY ://需要page, qo
                searchStrategy(qo, model);
                viewName = "index/searchStrategy";
                break;
            case SearchQueryObject.SEARCH_TRAVEL :
                searchTravel(qo, model);
                viewName = "index/searchTravel";
                break;
            case SearchQueryObject.SEARCH_USER :
                searchUser(qo, model);
                viewName = "index/searchUser";
                break;
            default:
                searchAll(qo, model);
                viewName = "index/searchAll";//需要data, qo
        }
        return viewName;
    }

    private void searchAll(SearchQueryObject qo, Model model){
        SearchResult page = new SearchResult();
        int total = 0;
        //将目的地和攻略/游记/用户查询出来
        Page<DestinationTemplate> dests = searchService.hightLightSearch(DestinationTemplate.INDEX_TYPE_NAME,
                DestinationTemplate.class, qo, "name", "info");
        Page<StrategyTemplate> strategys = searchService.hightLightSearch(StrategyTemplate.INDEX_TYPE_NAME,
                StrategyTemplate.class, qo, "title", "subtitle", "summary");
        Page<TravelTemplate> travels = searchService.hightLightSearch(TravelTemplate.INDEX_TYPE_NAME,
                TravelTemplate.class, qo, "title", "summary");
        Page<UserInfoTemplate> users = searchService.hightLightSearch(UserInfoTemplate.INDEX_TYPE_NAME,
                UserInfoTemplate.class, qo, "nickname", "destName");
        //加在一起
        page.setDests(dests.getContent());
        page.setStrategys(strategys.getContent());
        page.setTravels(travels.getContent());
        page.setUsers(users.getContent());
        //统计total
        total += dests.getTotalElements();
        total += strategys.getTotalElements();
        total += travels.getTotalElements();
        total += users.getTotalElements();
        page.setTotal(total);
        model.addAttribute("data", page);
    }
    private void searchUser(SearchQueryObject qo, Model model){
        Page<UserInfoTemplate> users = searchService.hightLightSearch(UserInfoTemplate.INDEX_TYPE_NAME,
                UserInfoTemplate.class, qo, "nickname", "destName");
        model.addAttribute("page", users);
    }

    private void searchTravel(SearchQueryObject qo, Model model){
        Page<TravelTemplate> travels = searchService.hightLightSearch(TravelTemplate.INDEX_TYPE_NAME,
                TravelTemplate.class, qo, "title", "summary");
        model.addAttribute("page", travels);
    }

    private void searchStrategy(SearchQueryObject qo, Model model){
        Page<StrategyTemplate> strategys = searchService.hightLightSearch(StrategyTemplate.INDEX_TYPE_NAME,
                StrategyTemplate.class, qo, "title", "subtitle", "summary");
        model.addAttribute("page", strategys);
    }

    private void searchDest(SearchQueryObject qo, Model model){
        //dest
        DestinationTemplate dest = destinationTemplateService.findByName(qo.getKeyword());
        model.addAttribute("dest", dest);
        int total = dest != null ? 1 : 0;
        //data
        Long destId = dest != null ? dest.getId() : null;
        List<StrategyTemplate> strategies = strategyTemplateService.findByDestId(destId);
        List<TravelTemplate> travels = travelTemplateService.findByDestId(destId);
        List<UserInfoTemplate> users = userInfoTemplateService.findByDestName(dest.getName());
        SearchResult data = new SearchResult();
        data.setStrategys(strategies);
        data.setTravels(travels);
        data.setUsers(users);
        //设置查询条数
        total += strategies.size() + travels.size() + users.size();
        data.setTotal(total);
        model.addAttribute("data", data);
    }


    @RequestMapping("/elasticsearch/init")
    @ResponseBody
    public String init(){
        //从MySQL查询得到目的地,攻略,游记,用户的信息
        //遍历封装到template中
        //将template存放进elasticsearch中(期间就会自动完成分词)
        List<StrategyDetail> details = strategyDetailService.selectAll();
        for (StrategyDetail detail : details) {
            Long destId = detail.getDest().getId();

            StrategyTemplate template = new StrategyTemplate();

            template.setId(detail.getId());
            template.setTitle(detail.getTitle());
            template.setSubTitle(detail.getSubTitle());
            template.setDestId(destId);
            template.setDestName(detail.getDest().getName());
            template.setThemeId(detail.getTheme().getId());
            template.setThemeName(detail.getTheme().getName());
            template.setSummary(detail.getSummary());
            template.setCreateTime(detail.getCreateTime());
            template.setViewnum(detail.getViewnum());
            template.setFavornum(detail.getFavornum());
            template.setReplynum(detail.getReplynum());
            template.setThumbsupnum(detail.getThumbsupnum());
            template.setCoverUrl(detail.getCoverUrl());

            Destination dest = destinationService.getCountry(destId);
            template.setCountryId(dest.getId());
            template.setCountryName(dest.getName());

            dest = destinationService.getProvince(destId);
            if (dest != null) {
                template.setProvinceId(dest.getId());
                template.setProvinceName(dest.getName());
            }

            strategyTemplateService.save(template);
        }

        //=========================================

        List<Travel> travels = travelService.list();
        for (Travel travel : travels) {
            TravelTemplate template = new TravelTemplate();
            template.setId(travel.getId());
            template.setAuthorId(travel.getAuthor().getId());
            template.setAuthorName(travel.getAuthor().getNickname());
            template.setDestId(travel.getDest().getId());
            template.setDestName(travel.getDest().getName());
            template.setTitle(travel.getTitle());
            template.setCreateTime(travel.getCreateTime());
            template.setCoverUrl(travel.getCoverUrl());
            template.setSummary(travel.getSummary());
            template.setReplynum(travel.getReplynum());
            template.setViewnum(travel.getViewnum());

            travelTemplateService.save(template);
        }

        //=========================================

        List<UserInfo> users = userInfoService.list();
        for (UserInfo user : users) {
            UserInfoTemplate template = new UserInfoTemplate();
            template.setId(user.getId());
            template.setNickname(user.getNickname());
            template.setDestName(user.getCity());
            template.setInfo(user.getInfo());
            template.setHeadUrl(user.getHeadImgUrl());
            template.setLevel(user.getLevel());

            userInfoTemplateService.save(template);
        }

        //=========================================

        List<Destination> dests = destinationService.list();
        for (Destination dest : dests) {
            DestinationTemplate template = new DestinationTemplate();
            template.setId(dest.getId());
            template.setName(dest.getName());
            template.setCoverUrl(dest.getCoverUrl());
            template.setInfo(dest.getInfo());

            destinationTemplateService.save(template);
        }
        return "ES的数据初始化完成";
    }
}
